package com.dmgis.hndz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dmgis.hndz.common.utils.DateTime;
import com.dmgis.hndz.common.utils.FileUtil;
import com.dmgis.hndz.mapper.Ybba01aMapper;
import com.dmgis.hndz.mapper.Zhaa11aMapper;
import com.dmgis.hndz.pojo.*;
import com.dmgis.hndz.sddz.dto.Ybba01bDTO;
import com.dmgis.hndz.service.Ybba01aService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @author PC
 * @description 针对表【Ybba01a(省级预警临时表)】的数据库操作Service实现
 * @createDate 2024-01-29 17:45:32
 */
@Service
public class Ybba01aServiceImpl extends ServiceImpl<Ybba01aMapper, Ybba01a>
        implements Ybba01aService {

    @Qualifier("mongoPrimaryTemplate")
    @Autowired
    private MongoTemplate mongoTemplate;

    @Value("${nginx.url}")
    private String nginxUrl;

    @Value("${nginx.filepath}")
    private String nginxFilepath;

    @Autowired
    private Ybba01aMapper ybba01aMapper;

    @Autowired
    private Zhaa11aMapper zhaa11aMapper;

    @Override
    public Object FbProduct(Ybba02a ybba02a) {
        Ybba01a ybba01a = new Ybba01a();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("YBBA01A020", 2);
        queryWrapper.eq("YBBA01A030", ybba02a.getYbba02a030());
        List<Ybba01a> list = baseMapper.selectList(queryWrapper);
        ybba01a.setYbba01a010(ybba02a.getYbba02a010());//id
        if (ybba02a.getYbba02a020().contains("短期")) {
            ybba01a.setYbba01a020(2);//产品类型 2代表短期 1代表短临
        } else {
            ybba01a.setYbba01a020(1);//产品类型 2代表短期 1代表短临
        }
        ybba01a.setYbba01a030(ybba02a.getYbba02a030());//时间
        String address2 = "";
        String address3 = "";
        String address4 = "";
        String address5 = "";
        String[] split1 = ybba02a.getYbba02a060().split(",");
        String[] split2 = ybba02a.getYbba02a070().split(",");//市
        String[] split3 = ybba02a.getYbba02a080().split(",");//县
        for (int i = 0; i < split1.length; i++) {
            String city = split2[i];
            String county = split3[i];
            if ("风险极大".equals(split1[i])) {
                address5 = address5.contains(city) ? address5 + county + "、" : (address5.length() > 0 ? address5.substring(0, address5.length() - 1) : address5) + (address5.equals("") ? "" : "，") + city + ":" + county + "、";
            } else if ("风险大".equals(split1[i])) {
                address4 = address4.contains(city) ? address4 + county + "、" : (address4.length() > 0 ? address4.substring(0, address4.length() - 1) : address4) + (address4.equals("") ? "" : "，") + city + ":" + county + "、";
            } else if ("风险较大".equals(split1[i])) {
                address3 = address3.contains(city) ? address3 + county + "、" : (address3.length() > 0 ? address3.substring(0, address3.length() - 1) : address3) + (address3.equals("") ? "" : "，") + city + ":" + county + "、";
            } else {
                address2 = address2.contains(city) ? address2 + county + "、" : (address2.length() > 0 ? address2.substring(0, address2.length() - 1) : address2) + (address2.equals("") ? "" : "，") + city + ":" + county + "、";
            }
        }
        if (address5 != "") {
            ybba01a.setYbba01a070(address5.substring(0, address5.length() - 1));//一级预警区域
        }
        if (address4 != "") {
            ybba01a.setYbba01a060(address4.substring(0, address4.length() - 1));//二级预警区域
        }
        if (address3 != "") {
            ybba01a.setYbba01a050(address3.substring(0, address3.length() - 1));//三级预警区域
        }
        if (address2 != "") {
            ybba01a.setYbba01a040(address2.substring(0, address2.length() - 1));//四级预警区域
        }
        String targetPath = nginxFilepath + ybba02a.getYbba02a020() + ".docx";
        ybba01a.setYbba01a120(ybba02a.getYbba02a020() + ".docx");
        ybba01a.setYbba01a140(ybba02a.getYbba02a090());//坐标
        String maxid = "";
        if (ybba02a.getYbba02a020().contains("短期")) {
            maxid = baseMapper.selectMaxDocByType("2");
        } else {
            maxid = baseMapper.selectMaxDocByType("1");
        }
        if (maxid == null || maxid == "") maxid = DateTime.now().toDateTimeString("yy") + "000";
        ybba01a.setYbba01a150(Integer.parseInt(maxid) + 1);//期号
        ybba01a.setYbba01a160(ybba02a.getYbba02a100());//预警内容

        int upcount = 0;
        if (list.size() == 0) {
            upcount = baseMapper.insert(ybba01a);
        } else {
            UpdateWrapper<Ybba01a> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("YBBA01A010", ybba01a.getYbba01a010());
            upcount = baseMapper.update(ybba01a, updateWrapper);
        }


        if (upcount > 0) {
            byte[] byteArray = FileUtil.getBytesByFile(targetPath);
            //保存到mongodb库中
            HyDocFile hyDocFile = new HyDocFile();
            hyDocFile.setData(byteArray);
            hyDocFile.setTable_name("doc_warn_product_city_file");
            hyDocFile.setId(String.valueOf(ybba02a.getYbba02a010()));

            //先查询出来数据 这里的is(id)可以改成in(ids) 即为批量删除
            Query query = new Query(Criteria.where("id").is(hyDocFile.getId()));
            //再根据查询删除
            mongoTemplate.remove(query, hyDocFile.getClass());
            mongoTemplate.save(hyDocFile);

            byte[] byteArray1 = FileUtil.getBytesByFile(targetPath.replace(".docx", ".jpg"));
            //保存到mongodb库中
            HyImageFile hyimgFile = new HyImageFile();
            hyimgFile.setData(byteArray1);
            hyimgFile.setTable_name("short_warn_product_jpg_file");
            hyimgFile.setId(String.valueOf(ybba02a.getYbba02a010()));
            //先查询出来数据 这里的is(id)可以改成in(ids) 即为批量删除
            Query query2 = new Query(Criteria.where("id").is(hyimgFile.getId()));
            //再根据查询删除
            mongoTemplate.remove(query2, hyimgFile.getClass());
            mongoTemplate.save(hyimgFile);
            return 1;
        }
        return 0;
    }

    @Override
    public List<Ybba01bDTO> getYj(String startTime, String endTime, Integer yjLevel) {
        List<Ybba01bDTO> ybba01bs = new ArrayList<>();
        List<Ybba01a> list = baseMapper.getYj(startTime, endTime, yjLevel);
        list.forEach(item -> {
            LocalDateTime ybba01a030 = item.getYbba01a030();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDate = ybba01a030.format(formatter);
            //Base64 Encoded
            String encoded = "";
            if (item.getYbba01a140() == null) {

            } else {
                byte[] ybba01a140 = (byte[]) item.getYbba01a140();
                encoded = new String(ybba01a140);
            }
            Ybba01bDTO build = Ybba01bDTO.builder()
                    .ybba01b010(item.getYbba01a010())
                    .ybba01b020(item.getYbba01a020())
                    .ybba01b030(formattedDate)
                    .ybba01b040(item.getYbba01a040())
                    .ybba01b050(item.getYbba01a050())
                    .ybba01b060(item.getYbba01a060())
                    .ybba01b070(item.getYbba01a070())
                    .ybba01b080(item.getYbba01a080())
                    .ybba01b090(item.getYbba01a090())
                    .ybba01b100(item.getYbba01a100())
                    .ybba01b110(item.getYbba01a110())
                    .ybba01b120(item.getYbba01a120())
                    .ybba01b130(item.getYbba01a130())
                    .ybba01b140(encoded)
                    .ybba01b150(item.getYbba01a150())
                    .ybba01b160(item.getYbba01a160())
                    .ybba01b035(item.getYbba01a035())
                    .ybba01b170("370000")
                    .ybba01b180("山东省国土空间生态修复中心")
                    .build();
            ybba01bs.add(build);
        });
        ybba01bs.sort(Comparator.comparing(Ybba01bDTO::getYbba01b030).reversed());
        return ybba01bs;
    }

    /**
     * 查询省级预警
     *
     * @param dateType 1：本年，2：本月，3：本日
     * @return
     */
    public List<Ybba01a> getYbba01aList(Integer dateType) {
        return ybba01aMapper.getYbba01aList(dateType);
    }

    /**
     * 预警灾害类型统计
     *
     * @return
     */
    public Map<String, Object> disasterTypeStatistics() {
        return zhaa11aMapper.disasterTypeStatistics();
    }
}